package com.soft.trading.service;

import android.accessibilityservice.AccessibilityService;

import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
public class AdvancedAccessibilityService extends AccessibilityService {
    private static final String TAG = "AdvancedAccessibilityService";

    // 单例模式，便于其他组件访问
    private static AdvancedAccessibilityService instance;

    // 目标App包名
    private String mTargetPackageName = "com.example.targetapp";
    private boolean mIsTargetAppForeground = false;
    private String mCurrentForegroundPackage = "";

    public static AdvancedAccessibilityService getInstance() {
        return instance;
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            handleWindowStateChanged(event);
        }
    }

    private void handleWindowStateChanged(AccessibilityEvent event) {
        if (event.getPackageName() != null && event.getClassName() != null) {
            String packageName = event.getPackageName().toString();
            String className = event.getClassName().toString();

            // 更新当前前台应用信息
            mCurrentForegroundPackage = packageName;
            mIsTargetAppForeground = packageName.equals(mTargetPackageName);

            Log.d(TAG, "当前前台应用: " + packageName + ", 类名: " + className);
            Log.d(TAG, "目标应用在前台: " + mIsTargetAppForeground);
        }
    }

    @Override
    public void onInterrupt() {
        Log.e(TAG, "无障碍服务被中断");
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        instance = this;
        Log.d(TAG, "无障碍服务已连接");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        instance = null;
        Log.d(TAG, "无障碍服务已销毁");
    }

    // 判断目标App是否在前台
    public boolean isTargetAppForeground() {
        return mIsTargetAppForeground;
    }

    // 获取当前前台应用包名
    public String getCurrentForegroundPackage() {
        return mCurrentForegroundPackage;
    }
}